package com.android.example.app3;

import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Gitee API 辅助类，用于获取应用版本信息
 */
public class GiteeApiHelper {
    private static final String TAG = "GiteeApiHelper";
    private static final String GITEE_API_URL = "https://gitee.com/api/v5/repos/li-guansheng/app3/releases/";
    private static final String OWNER = "liguansheng"; // 替换为你的Gitee用户名
    private static final String REPO = "app3"; // 替换为你的Gitee仓库名
    private static final String TOKEN = "d9d55414937ffc71bd5ce0dff1876a8f"; // 替换为你的Gitee私人令牌

    private OkHttpClient client;
    private VersionInfoCallback callback;


    /**
     * 获取最新版本信息
     */
    public void getLatestVersionInfo() {
        // 构建请求URL，使用 String.format 替换占位符
        String url = String.format(GITEE_API_URL);
        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "token " + TOKEN)
                .build();

        // 发送异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 请求失败
                Log.e(TAG, "Request failed: " + e.getMessage());
                if (callback != null) {
                    callback.onError("请求失败: " + e.getMessage());
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                if (!response.isSuccessful()) {
                    // 请求不成功
                    Log.e(TAG, "Unexpected code: " + response);
                    if (callback != null) {
                        callback.onError("请求不成功: " + response.code());
                    }
                    return;
                }

                // 获取响应体
                String responseData = null;
                if (response.body() != null) {
                    responseData = response.body().string();
                }
                Log.d(TAG, "Response data: " + responseData);

                // 解析版本信息
                VersionInfo versionInfo = parseVersionInfo(responseData);

// 回调成功
                if (callback != null) {
                    callback.onSuccess(versionInfo);
                }

            }
        });
    }

    /**
     * 构造方法
     *
     * @param callback 版本信息回调接口
     */
    public GiteeApiHelper(VersionInfoCallback callback) {
        this.client = new OkHttpClient();
        this.callback = callback;
    }

    /**
     * 解析版本信息
     *
     * @param responseData 响应数据
     * @return 解析后的版本信息
     */
    private VersionInfo parseVersionInfo(String responseData) {
        try {
            JSONArray jsonArray = new JSONArray(responseData);
            StringBuilder result = new StringBuilder();
            if (jsonArray.length() > 0) {

                String downloadUrl = null;

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String tagName = jsonObject.getString("tag_name");
                    String name = jsonObject.getString("name");
                    String body = jsonObject.getString("body");
                    downloadUrl = jsonObject.getJSONArray("assets").getJSONObject(0).getString("browser_download_url");

                    result.append("版本名称: ").append(tagName).append("\n")
                            .append("版本描述: ").append(name).append("\n")
                            .append("更新说明: ").append(body).append("\n")
                            .append("下载地址: ").append(downloadUrl).append("\n\n");
                }


                String displayText = String.valueOf(result);

                return new VersionInfo(displayText, downloadUrl);
            }
            return new VersionInfo("未找到发布信息", null);
        } catch (Exception e) {
            Log.e(TAG, "解析版本信息失败: " + e.getMessage());
            return new VersionInfo("解析版本信息失败", null);
        }
    }

    /**
     * 版本信息回调接口
     */
    public interface VersionInfoCallback {
        void onSuccess(VersionInfo versionInfo);
        void onError(String errorMessage);
    }

    public static class VersionInfo {
        private String displayText;
        private String downloadUrl;

        public VersionInfo(String displayText, String downloadUrl) {
            this.displayText = displayText;
            this.downloadUrl = downloadUrl;
        }

        public String getDisplayText() {
            return displayText;
        }

        public String getDownloadUrl() {
            return downloadUrl;
        }
    }


}
